package com.xhej.rowreat.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ResourceUtils;

import com.xhej.rowreat.model.Bank;

public class Utils {
	
	static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
	
	private static ApplicationContext applicationContext;
	 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		 Utils.applicationContext = applicationContext;
	 }
	 public static ApplicationContext getApplicationContext() {
	  return applicationContext;
	 }
	
	//JavaBean转换为Map  
		public static Map<String,Object> bean2map(Object bean,Class<?> beanClass) {  
		    Map<String,Object> map = new HashMap<>();  
		    //获取指定类的BeanInfo 对象  
		    BeanInfo beanInfo = null;
			try {
				beanInfo = Introspector.getBeanInfo(beanClass, Object.class);
			} catch (IntrospectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		    //获取所有的属性描述器  
		    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();  
		    for(PropertyDescriptor pd:pds){  
		        String key = pd.getName();  
		        Method getter = pd.getReadMethod();  
		        Object value = null;
				try {
					value = getter.invoke(bean);
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
		        map.put(key, value);  
		    }  
		    return map;  
		} 
		
		//Map转换为JavaBean  
		public static <T> T map2bean(Map<String,Object> map,Class<T> clz) throws Exception{  
		    //创建JavaBean对象  
		    T obj = clz.newInstance();  
		    //获取指定类的BeanInfo对象  
		    BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);  
		    //获取所有的属性描述器  
		    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();  
		    for(PropertyDescriptor pd:pds){  
		        Object value = map.get(pd.getName());  
		        Method setter = pd.getWriteMethod();  
		        setter.invoke(obj, value);  
		    }  
		    
		      
		    return  obj;  
		    
		    
//		    BeanInfo beanInfo = Introspector.getBeanInfo(clz); // 获取类属性    
//	        Object obj = type.newInstance(); // 创建 JavaBean 对象    
//	    
//	        // 给 JavaBean 对象的属性赋值    
//	        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();    
//	        for (int i = 0; i< propertyDescriptors.length; i++) {    
//	            PropertyDescriptor descriptor = propertyDescriptors[i];    
//	            String propertyName = descriptor.getName();    
//	    
//	            if (map.containsKey(propertyName)) {    
//	                // 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。    
//	                Object value = map.get(propertyName);    
//	    
//	                Object[] args = new Object[1];    
//	                args[0] = value;    
//	    
//	                descriptor.getWriteMethod().invoke(obj, args);    
//	            }    
//	        }    
//	        return obj; 
		}  
		
		//公式计算 
		public static Double functionCalculation(String str,double dimensionVal) {  
			double  weightVal=0; 
		    try {
		    	weightVal = (Double) jse.eval(str.replaceAll("A", dimensionVal+""));
			} catch (ScriptException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		    
		    return weightVal;
		} 
		
		
		
		//读取excel文件
		@SuppressWarnings("unused")
		@Test
		public static List<Map<String,Object>> readExcel(String path){ 
			
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		    HSSFWorkbook book = null;
			try {
				book = new HSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:"+path)));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    HSSFSheet sheet = book.getSheetAt(0); 
		    // 循环sheet中的列获取第一行所有的列名
		    HSSFRow rowtitle = sheet.getRow(0);
		    // 定义常量名
		    List<String> listName = new ArrayList<>();
		    for(int i =0;i>-1;i++) {
		    	if(rowtitle.getCell(i)!=null){
		    		rowtitle.getCell(i).setCellType(Cell.CELL_TYPE_STRING);
		    		listName.add(rowtitle.getCell(i).getStringCellValue());
		       } else {
		    	   break;
		       }
		    }
		    // 循环行
		    for(int i=1; i<sheet.getLastRowNum()+1; i++) {
		        HSSFRow row = sheet.getRow(i);
		        HashMap<String, Object> map = new HashMap<String, Object>();
		       
		        // 循环列
		        for(int j =0;j<listName.size();j++) {
		        	// 定义单元格文字类型
		        	row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
		        	// 获取当前单元格数据
		        	map.put(listName.get(j), (Object)row.getCell(j).getStringCellValue());
		        }
		        list.add(map);
		    }
		    return list;
		}
		
		//读取单列excel文件
		@SuppressWarnings({ "unused", "null" })
		@Test
		public static List<String> readExcelOne(String path){ 
			
			List<String> list = new ArrayList<String>();
		    HSSFWorkbook book = null;
			try {
				book = new HSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:"+path)));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    HSSFSheet sheet = book.getSheetAt(0); 
		   
		    // 循环行
		    for(int i=1; i<sheet.getLastRowNum()+1; i++) {
		        HSSFRow row = sheet.getRow(i);
		        if(row==null||row.getCell(0)==null) {
		        	break;
		        }
	        	// 定义单元格文字类型
	        	row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
	        	// 获取当前单元格数据
		        list.add((String)row.getCell(0).getStringCellValue());
		    }
		    return list;
		}
		
		
		@SuppressWarnings("unchecked")
		public static void sortListBySingleMapKey(List dataList, Object sortKey, boolean descend) {
			// 排序
			Collections.sort(dataList,new Comparator<Map>() {
		        @Override
		        public int compare(Map o1, Map o2) {
		            int ret = 0;
		            //比较两个对象的顺序，如果前者小于、等于或者大于后者，则分别返回-1/0/1
//		            ret = o1.get("translate").toString().compareTo(o2.get("translate").toString());//逆序的话就用o2.compareTo(o1)即可
		            // 升序
		            if(descend) {
		            	ret = (new BigDecimal(o1.get(sortKey).toString())).compareTo((new BigDecimal(o2.get(sortKey).toString())));
		            } else {
		            	ret = (new BigDecimal(o2.get(sortKey).toString())).compareTo((new BigDecimal(o1.get(sortKey).toString())));
		            }
		            
		            return ret;
		        }
		    });
		}
		
	public static boolean isNullOrEmpty(Object obj) {
		if (obj instanceof Object[]) {
			Object[] o  = (Object[]) obj;
			for (int i  = 0; i < o.length; i++) {
				Object object = o[i];
				if(object instanceof Date) {
					if(object.equals(new Date(0))) {
						return true;
					}else if ((obj == null) || (("").equals(obj))) {
						return true;
					}
				}
			}
		} else {
			if (obj instanceof Date) {
				if (obj.equals(new Date(0))) {
					return true;
				} else if ((obj == null) || (("").equals(obj)) || (("null").equals(obj)) ) {
					return true;
				}
			}
		}
		return false;
	}
}
